

package com.hazelcast.jet.impl.deployment;

import com.hazelcast.jet.core.AbstractProcessor;
import com.hazelcast.jet.core.Processor;

import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.List;

import static org.junit.Assert.fail;

public class LoadClassesIsolated extends AbstractProcessor {

    static volatile AssertionError assertionErrorInClose;
    private final boolean shouldComplete;
    private final List<String> onClasspath;
    private final List<String> notOnClasspath;

    LoadClassesIsolated(boolean shouldComplete) {
        this.shouldComplete = shouldComplete;
        onClasspath = new ArrayList<>();
        onClasspath.add("com.sample.pojo.person.Person$Appereance");
        notOnClasspath = new ArrayList<>();
        notOnClasspath.add("com.sample.pojo.car.Car");
    }

    LoadClassesIsolated(List<String> onClasspath, List<String> notOnClasspath, boolean shouldComplete) {
        this.onClasspath = onClasspath;
        this.notOnClasspath = notOnClasspath;
        this.shouldComplete = shouldComplete;
    }

    @Override
    protected void init(@Nonnull Processor.Context context) {
        checkLoadClass();
    }

    @Override
    public boolean complete() {
        checkLoadClass();
        return shouldComplete;
    }

    @Override
    public void close() {
        try {
            checkLoadClass();
        } catch (AssertionError e) {
            assertionErrorInClose = e;
        }
    }

    private void checkLoadClass() {
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        for (String classname : onClasspath) {
            try {
                cl.loadClass(classname);
            } catch (ClassNotFoundException e) {
                fail(e.getMessage());
            }
        }
        for (String classname : notOnClasspath) {
            try {
                cl.loadClass(classname);
                fail();
            } catch (ClassNotFoundException ignored) {
            }
        }
    }
}
